package fun.lifepoem.blog.utils;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PullResult;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.treewalk.CanonicalTreeParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * @author Yiwyn
 * @create 2022/10/31 20:50
 */
@Component
@Slf4j
public class GitUtils {

    @Value("${git.repository-path}")
    private String repositoryPath;

    @Value("${git.remote-repository-url}")
    private String remoteRepositoryUrl;

    @Value("${git.branch}")
    private String branch;


    private Git git;

    /**
     * 获取本地git仓库
     */
    private Git getGit() throws Exception {
        if (git == null) {
            File file = new File(repositoryPath);
            if (file.exists()) {
                git = new Git(new FileRepository(new File(repositoryPath + "/.git")));
            } else {
                git = Git.cloneRepository()
                        .setURI(remoteRepositoryUrl)
                        .setBranch(branch)
                        .setDirectory(file).call();
            }
        }
        return git;
    }

    public void pullRepository() throws Exception {
        Git git = getGit();
        PullResult result = git.pull().setRemote("origin").setRemoteBranchName(branch).call();
        log.info(result.toString());
    }


    /**
     * 获取提交log
     *
     * @return
     * @throws Exception
     */
    public List<DiffEntry> getGitLog() throws Exception {
        Git git = getGit();
        Repository repository = git.getRepository();

        ObjectId oldHead = repository.resolve("HEAD^^{tree}");
        ObjectId head = repository.resolve("HEAD^{tree}");
        try (ObjectReader reader = repository.newObjectReader()) {
            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);
            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, head);

            // finally get the list of changed files
            try (Git g = new Git(repository)) {
                List<DiffEntry> diffs = g.diff()
                        .setNewTree(newTreeIter)
                        .setOldTree(oldTreeIter)
                        .call();
                return diffs;
            }
        }
    }

}
